package com.example.crop_image_project

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.Base64
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.dawn.monsterabc.CustomServicePlugin
import com.example.crop_image_project.BitmapUtil.decodeResource
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

class MainActivity : FlutterActivity() {

    val CHANNEL: String = "com.example.crop_image_project/asset_channel"

    var mIvOrigin: ImageView? = null
    var mIvMask: ImageView? = null

    var mIvCropResult: ImageView? = null

    var mTvCrop: TextView? = null

    var mProgressDialog: LoadingProgressDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//
//        setContentView(R.layout.activity_main)
//        initViews()
    }

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        flutterEngine.plugins.add(CustomServicePlugin(this))
        MethodChannel(
            flutterEngine.dartExecutor.binaryMessenger, CHANNEL
        ).setMethodCallHandler { call, result ->
            when (call.method) {
                "processImages" -> {
                    val imageString1 = call.argument<String>("image1")
                    val imageString2 = call.argument<String>("image2")
                    imageString1?.let {
                        handleImage(it, imageString2, result)
                    } ?: result.error("IMAGE_ERROR", "Image data is null", null)
                }

                else -> result.notImplemented()
            }
        }
    }

    private fun handleImage(
        encodedImage1: String,
        encodedImage2: String?,
        result: MethodChannel.Result
    ) {
        val decodedBytes1 = Base64.decode(encodedImage1, Base64.DEFAULT)
        val decodedBytes2 = Base64.decode(encodedImage2, Base64.DEFAULT)

        val maskBitMap = BitmapFactory.decodeByteArray(decodedBytes1, 0, decodedBytes1.size)
        val originBitMap = BitmapFactory.decodeByteArray(decodedBytes2, 0, decodedBytes2.size)

        var bitmapShow = BitmapUtil.cropContour(originBitMap, maskBitMap)
        val filePath = saveBitmap(bitmapShow)
        result.success(filePath)
    }


    /**
     * 保存bitmap到本地
     */
    private fun saveBitmap(bitmap: Bitmap): String {
        val file = File(getExternalFilesDir(null), "processed_image.png")
        try {
            FileOutputStream(file).use { output ->
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, output)
            }
        } catch (e: IOException) {
            throw RuntimeException(e)
        }
        return file.absolutePath
    }


    fun initViews() {
        mIvOrigin = findViewById(R.id.iv_origin)
        mIvMask = findViewById(R.id.iv_mask)
        mIvCropResult = findViewById(R.id.iv_crop_result)
        mTvCrop = findViewById(R.id.tv_crop)
        mTvCrop.let {
            if (PermissionUtils.verifyReadAndWritePermissions(this@MainActivity, 100)) {
                showProgress("处理中")
                object : Thread() {
                    override fun run() {
                        super.run()
                        crop()
                    }
                }.start()
            } else {
                Toast.makeText(this@MainActivity, "没有存储权限", Toast.LENGTH_SHORT).show()
            }
        }
    }


    /**
     * 裁剪
     */
    private fun crop() {
        var bitmapShow: Bitmap? = null
        val originalBitmap: Bitmap = decodeResource(this, R.mipmap.origin)
        val maskBitmap: Bitmap = decodeResource(this, R.mipmap.mask)
        bitmapShow = BitmapUtil.cropContour(originalBitmap, maskBitmap)

        val finalBitmapShow = bitmapShow
        runOnUiThread {
            hideProgress()
            mIvCropResult!!.setImageBitmap(finalBitmapShow)
        }
    }

    fun showProgress(text: CharSequence?) {
        runOnUiThread {
            mProgressDialog = LoadingProgressDialog.show(this@MainActivity, null, text)
        }
    }

    fun hideProgress() {
        if (mProgressDialog != null && mProgressDialog!!.getWindow() != null) {
            runOnUiThread {
                if (mProgressDialog != null) {
                    mProgressDialog!!.dismiss()
                }
            }
        }
    }
}
